<?php

namespace App\Http\Controllers;

use App\Models\ChatCount;
use App\Models\ChatKey;
use App\Models\ChatMsg;
use App\Models\ChatUser;
use App\Models\OnlineUser;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Support\Facades\DB;

class ChatController extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    // 聊天服务
    // 添加用户
    public function add(Request $request)
    {
        $userid = $request->input('userid');
        $name = $request->input('name');
        $iconurl = $request->input('iconurl');
        $user = new ChatUser();
        $user->userid = $userid;
        $user->name = $name;
        $user->iconurl = $iconurl;
        $err = $user->where('userid', $userid)->get();
        if (count($err) > 0) {
            return response()->json([
                'code' => 201,
                'msg' => '该用户已注册',
            ]);
        }
        $data = $user->save();
        return response()->json([
            'code' => 200,
            'msg' => 'ok',
            'data' => $data,
        ]);

    }
    //查询十个测试用户
    public function gettestuser(Request $request){
        $user = new ChatUser();
        $data = $user
        ->offset(0)
        ->limit(10)
        ->get();
        return response()->json([
            'code' => 200,
            'data' => $data,
        ]);
    }



    // 聊天用户上线登录
    public function goOnline(Request $request)
    {
        $userid = $request->input('userid');
        $user = new ChatUser();
        $userOne = $user->where('userid', $userid)->get();
        if (sizeof($userOne) == 0) {
            return response()->json([
                'code' => 201,
                'msg' => '未找到该用户',
            ]);
        }
        $this->userOnline($userid);
        return response()->json([
            'code' => 200,
            'data' => $userOne,
        ]);
    }

    // 聊天用下线
    public function outline(Request $request)
    {
        $userid = $request->input('userid');
        $user = new ChatUser();
        $userOne = $user->where('userid', $userid)->get();
        if (sizeof($userOne) == 0) {
            return response()->json([
                'code' => 201,
                'msg' => '未找到该用户',
            ]);
        }
        $this->userOutline($userid);
        return response()->json([
            'code' => 200,
            'data' => $userOne,
        ]);
    }







    // A发送消息给B
    public function sendmsg(Request $request)
    {

        $ChatUser = new ChatUser();
        $userid_a = $request->input('userid_a');
        $userid_b = $request->input('userid_b');
        $content = $request->input('content');
        $flage = $ChatUser->where('userid', $userid_b)->count();
        if (!$flage) {
            return response()->json([
                'code' => 201,
                'data' => $userid_b . '用户未注册',
            ]);
        }
        $this->userOnline($userid_a);
        $ChatCount = new ChatCount();
        $ChatMsg = new ChatMsg();
        $chatkey = $userid_a . $userid_b;
        $ChatMsg->chatkey = $chatkey;
        $ChatMsg->sender = $userid_a;
        $ChatMsg->recipient = $userid_b;
        $ChatMsg->content = $content;
        $ChatMsg->timer = Time();
        $ChatMsgs = $ChatMsg->save();
        //添加记录信息
        $count = $ChatCount->where('sender', $userid_a)
            ->where('recipient', $userid_b)
            ->get();
        if (count($count) > 0) {
            //以前记录过
            $this->autoupdatemsgcount($userid_a, $userid_b);

        } else {
            //新纪录
            $ChatCount->counts = 1;
            $ChatCount->sender = $userid_a;
            $ChatCount->recipient = $userid_b;
            $ChatCount->save();
            $ChatCount2 = new ChatCount();
            $ChatCount2->counts = 0;
            $ChatCount2->sender = $userid_b;
            $ChatCount2->recipient = $userid_a;
            $ChatCount2->save();
        }

        if ($ChatMsgs) {
            $ChatUser->where('userid', $userid_b)
                ->update(['newmsg' => 1]);

            return response()->json([
                'code' => 200,
                'data' => new ChatMsg([
                    'id' => $ChatMsg->id,
                    'content' => $ChatMsg->content,
                    'imgurl' => $ChatMsg->imgurl,
                    'timer' => $ChatMsg->timer,
                ]),
            ]);
        } else {
            return response()->json([
                'code' => 201,
                'data' => '发送失败',
            ]);
        }

    }

    // A撤回一条消息
    public function recallmsg(Request $request)
    {

        $userid = $request->input('userid');
        $msgid = $request->input('msgid');

        if (!$msgid || !$userid) {
            return response()->json([
                'code' => 201,
                'data' => "userid,msgid参数不全",
            ]);
        }
        $ChatMsg = new ChatMsg();
        $res = $ChatMsg->where('sender', $userid)
            ->where('id', $msgid)
            ->update(['display' => 0]);
        return response()->json([
            'code' => 200,
            'data' => $res,
        ]);
    }

    // 阅读A与B已经接收的条数
    public function updatecount(Request $request)
    {

        $userid_a = $request->input('userid_a');
        $userid_b = $request->input('userid_b');

        if (!$userid_a || !$userid_b) {
            return response()->json([
                'code' => 201,
                'data' => "userid_a,userid_b参数不全",
            ]);
        }

        $count = $this->autoupdatemsgcount($userid_a, $userid_b);
        return response()->json([
            'code' => 200,
            'data' => $count,
        ]);

    }

    // 查询a和b聊天记录
    public function findABchat(Request $request)
    {
        $pagesize = $request->input('pagesize');
        $page = $request->input('page');

        if (!$pagesize || !$page) {
            return response()->json([
                'code' => 201,
                'data' => "pagesize,page参数不全",
            ]);
        }
        $pagesize = intval($pagesize);
        $page = intval($page);
        $offset = ($page - 1) * $pagesize;
        $limit = $pagesize;
        $ChatMsg = new ChatMsg();
        $userid_a = $request->input('userid_a');
        $userid_b = $request->input('userid_b');
        $chatkey1 = $userid_a . $userid_b;
        $chatkey2 = $userid_b . $userid_a;
        $chats = $ChatMsg
            ->where('display', 1)
            ->Where(function ($query) use ($chatkey1, $chatkey2) {
                $query->Where('chatkey', $chatkey1)
                    ->orWhere('chatkey', $chatkey2);
            })
            ->orderBy('timer', 'desc')
            ->offset($offset)
            ->limit($limit)
            ->get(['id', 'sender', 'recipient', 'content', 'imgurl', 'timer']);
        $data = array();
        foreach ($chats as $item) {
            $obj = new ChatMsg();
            $obj->userid = $item->sender;
            $obj->content = $item->content;
            $obj->imgurl = $item->imgurl;
            $obj->timer = $item->timer;
            array_push($data, $obj);
        }

        if (sizeof($data) > 0) {
            $this->upuserOnline($userid_a, $userid_b);
        }

        return response()->json([
            'code' => 200,
            'data' => $data,
        ]);
    }

    // 【实时刷新】a和b一对一聊天查询
    public function findTimeMsglist(Request $request)
    {
        $userid_a = $request->input('userid_a');
        $userid_b = $request->input('userid_b');
        if (!$userid_a || !$userid_b) {
            return response()->json([
                'code' => 201,
                'data' => "userid_a,userid_b参数不全",
            ]);
        }
        $count = DB::table('chat_users')
            ->where('userid', $userid_a)
            ->where('newmsg', 1)
            ->count();
        if ($count == 0) {
            return response()->json([
                'code' => 201,
                'msg' => '无新消息',
                'data' => [],
            ]);
        }

        $ChatMsgs = DB::table('chatmsgs')
            ->where('display', '=', 1)
            ->where('sender', '=', $userid_b)
            ->where('recipient', '=', $userid_a)
            ->join('online_users', function ($join) {
                $join->on('chatmsgs.sender', '=', 'online_users.userid')
                    ->on('chatmsgs.timer', '>', 'online_users.onlinetimer');
            })

            ->get(['id', 'sender', 'recipient', 'content', 'imgurl', 'timer']);
        $data = array();
        foreach ($ChatMsgs as $item) {
            $obj = new ChatMsg();
            $obj->userid = $item->sender;
            $obj->content = $item->content;
            $obj->imgurl = $item->imgurl;
            $obj->timer = $item->timer;
            array_push($data, $obj);
        }
        if (sizeof($data) > 0) {
            $this->upuserOnline($userid_a, $userid_b);
        }

        return response()->json([
            'code' => 200,
            'ChatMsgs' => $ChatMsgs,
            'data' => $data,
        ]);

    }

    // 【实时刷新】消息列表查询
    public function findTimelist(Request $request)
    {

        $userid_a = $request->input('userid_a');
        $count = DB::table('chat_users')
            ->where('userid', $userid_a)
            ->where('newmsg', 1)
            ->count();
        if ($count == 0) {
            return response()->json([
                'code' => 201,
                'msg' => '无新消息',
                'data' => [],
            ]);
        }
        $ChatMsg = new ChatMsg();
        $ChatCount = new ChatCount();
        // 总消息量
        $Chats = $ChatMsg
            ->where('display', 1)
            ->Where(function ($query) use ($userid_a) {
                $query->Where('sender', $userid_a)
                    ->orWhere('recipient', $userid_a);
            })
            ->orderBy('timer', 'desc')
            ->get(['recipient', 'sender', 'content', 'imgurl']);

        $no_rev = 0; //未接收总量
        $data = array();
        $tag = array(); //记录用户id作用去重
        $User = new ChatUser();
        foreach ($Chats as $value) {
            if ($value->sender == $userid_a) {
                //自己的消息，存别人（带上recipient的昵称和头像）
                if (!in_array($value->recipient, $tag)) {
                    $users = $User->where('userid', $value->recipient)->first(['userid', 'name', 'iconurl']);
                    //处理未接收条数
                    $chatkey1 = $userid_a . $value->recipient;
                    $chatkey2 = $value->recipient . $userid_a;
                    $count1 = $ChatMsg
                        ->where('display', 1)
                        ->Where(function ($query) use ($chatkey1, $chatkey2) {
                            $query->Where('chatkey', $chatkey1)
                                ->orWhere('chatkey', $chatkey2);
                        })
                        ->count();
                    $count2 = $ChatCount->where('sender', $userid_a)
                        ->where('recipient', $value->recipient)
                        ->get()[0]->counts;
                    $users->content = $value->content;
                    $users->num = $count1 - $count2;
                    $users->imgurl = $value->imgurl;
                    $no_rev = $no_rev + $users->num;
                    array_push($data, $users);
                    array_push($tag, $value->recipient);
                }
            } else {
                //B用户发的消息,存自己（带上sender的昵称和头像）
                if (!in_array($value->sender, $tag)) {
                    $users = $User->where('userid', $value->sender)->first(['userid', 'name', 'iconurl']);

                    //处理未接收条数
                    $chatkey1 = $userid_a . $value->sender;
                    $chatkey2 = $value->sender . $userid_a;
                    $count1 = $ChatMsg
                        ->where('display', 1)
                        ->Where(function ($query) use ($chatkey1, $chatkey2) {
                            $query->Where('chatkey', $chatkey1)
                                ->orWhere('chatkey', $chatkey2);
                        })
                        ->count();
                    $count2 = $ChatCount->where('sender', $userid_a)
                        ->where('recipient', $value->sender)
                        ->get()[0]->counts;

                    $users->content = $value->content;
                    $users->num = $count1 - $count2;
                    $users->imgurl = $value->imgurl;
                    $no_rev = $no_rev + $users->num;
                    array_push($data, $users);
                    array_push($tag, $value->sender);
                }
            }

        }
        return response()->json([
            'code' => 200,
            'num' => $no_rev,
            'data' => $data,
        ]);
    }

    // 消息列表查询
    public function findMsglist(Request $request)
    {
        $ChatMsg = new ChatMsg();
        $ChatCount = new ChatCount();
        $userid_a = $request->input('userid_a');

        // 总消息量
        $Chats = $ChatMsg
            ->where('display', 1)
            ->Where(function ($query) use ($userid_a) {
                $query->Where('sender', $userid_a)
                    ->orWhere('recipient', $userid_a);
            })
            ->orderBy('timer', 'desc')
            ->get(['recipient', 'sender', 'content', 'imgurl']);

        $no_rev = 0; //未接收总量
        $data = array();
        $tag = array(); //记录用户id作用去重
        $User = new ChatUser();
        foreach ($Chats as $value) {
            if ($value->sender == $userid_a) {
                //自己的消息，存别人（带上recipient的昵称和头像）
                if (!in_array($value->recipient, $tag)) {
                    $users = $User->where('userid', $value->recipient)->first(['userid', 'name', 'iconurl']);
                    //处理未接收条数
                    $chatkey1 = $userid_a . $value->recipient;
                    $chatkey2 = $value->recipient . $userid_a;
                    $count1 = $ChatMsg
                        ->where('display', 1)
                        ->Where(function ($query) use ($chatkey1, $chatkey2) {
                            $query->Where('chatkey', $chatkey1)
                                ->orWhere('chatkey', $chatkey2);
                        })
                        ->count();
                    $count2 = $ChatCount->where('sender', $userid_a)
                        ->where('recipient', $value->recipient)
                        ->get()[0]->counts;
                    $users->content = $value->content;
                    $users->num = $count1 - $count2;
                    $users->imgurl = $value->imgurl;
                    $no_rev = $no_rev + $users->num;
                    array_push($data, $users);
                    array_push($tag, $value->recipient);
                }
            } else {
                //B用户发的消息,存自己（带上sender的昵称和头像）
                if (!in_array($value->sender, $tag)) {
                    $users = $User->where('userid', $value->sender)->first(['userid', 'name', 'iconurl']);

                    //处理未接收条数
                    $chatkey1 = $userid_a . $value->sender;
                    $chatkey2 = $value->sender . $userid_a;
                    $count1 = $ChatMsg
                        ->where('display', 1)
                        ->Where(function ($query) use ($chatkey1, $chatkey2) {
                            $query->Where('chatkey', $chatkey1)
                                ->orWhere('chatkey', $chatkey2);
                        })
                        ->count();
                    $count2 = $ChatCount->where('sender', $userid_a)
                        ->where('recipient', $value->sender)
                        ->get()[0]->counts;

                    $users->content = $value->content;
                    $users->num = $count1 - $count2;
                    $users->imgurl = $value->imgurl;
                    $no_rev = $no_rev + $users->num;
                    array_push($data, $users);
                    array_push($tag, $value->sender);
                }
            }

        }
        return response()->json([
            'code' => 200,
            'num' => $no_rev,
            'data' => $data,
        ]);
    }

    //【函数】更新聊天记录
    private static function autoupdatemsgcount(string $userid_a, string $userid_b)
    {
        $ChatMsg = new ChatMsg();
        $ChatCount = new ChatCount();
        $chatkey1 = $userid_a . $userid_b;
        $chatkey2 = $userid_b . $userid_a;

        $count = $ChatMsg
            ->where('display', 1)
            ->Where(function ($query) use ($chatkey1, $chatkey2) {
                $query->Where('chatkey', $chatkey1)
                    ->orWhere('chatkey', $chatkey2);
            })

            ->count();

        return $ChatCount->where('sender', $userid_a)
            ->where('recipient', $userid_b)
            ->update(['counts' => $count]);
    }

    //【函数】上线
    private static function userOnline(string $userid)
    {
        if (!$userid) {
            return false;
        }
        $OnlineUser = new OnlineUser();

        try {
            $count = $OnlineUser->where('userid', $userid)->count();
            if ($count) {
                return $OnlineUser->where('userid', $userid)
                    ->update(['onlinetimer' => Time() - 1]);
            } else {
                $OnlineUser->userid = $userid;
                $OnlineUser->onlinetimer = Time();
                return $OnlineUser->save();
            }

        } catch (\Throwable $th) {
            return false;
        }

    }

    //【函数】刷新在线时间
    private static function upuserOnline(string $userid_a, string $userid_b)
    {
        if (!$userid_b) {
            return false;
        }
        $OnlineUser = new OnlineUser();
        $ChatUser = new ChatUser();
        try {
            $count = $OnlineUser->where('userid', $userid_b)->count();
            if (!$count) {
                return false;
            }
            $ChatUser->where('userid', $userid_a)
                ->update(['newmsg' => 0]);
            return $OnlineUser->where('userid', $userid_b)
                ->update(['onlinetimer' => Time()]);
        } catch (\Throwable $th) {
            return false;
        }

    }

    //【函数】线下
    private static function userOutline(string $userid)
    {
        if (!$userid) {
            return false;
        }
        $OnlineUser = new OnlineUser();
        $OnlineUser->userid = $userid;
        try {
            return $OnlineUser->where('userid', $userid)->delete();
        } catch (\Throwable $th) {
            return false;
        }

    }

}
